//
//  LeftController.m
//  RRQS
//
//  Created by kyjun on 16/3/23.
//
//

#import "LeftController.h"
#import "LeftCell.h"
#import "Login.h"
#import "HBHUDTool.h"
#import "UIImageView+WebCache.h"


#define Main_Width  (SCREEN_WIDTH/2 + Menu_CenterWidth)


@interface LeftController ()<UIGestureRecognizerDelegate>
@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UIButton* btnUser;
@property(nonatomic,strong) UIImageView* imageIcon;
@property(nonatomic,strong) UILabel* labelUser;
@property(nonatomic,strong) UIImageView* iconArrow;

@property(nonatomic,strong) UIView* statuView;
@property(nonatomic,strong) UIButton* btnOpen;
@property(nonatomic,strong) UIButton* btnClose;
@property(nonatomic,strong) UIButton* btnBusy;

@property(nonatomic,strong) NSArray* arrayTitle;
@property(nonatomic,strong) NSArray* arrayIcon;

@property(nonatomic,strong) NSString* cellIdentifier;

@property(nonatomic,strong) MMember* item;
@end

@implementation LeftController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrayIcon = @[@"icon_left_renwu",@"icon_left_paotui",@"icon_left_yue",@"icon_left_tongji",@"icon_left_paihang",@"icon_left_kaoqin",@"icon_left_tongzhi",@"icon_left_setting",@"icon_left_yichang"];
    self.arrayTitle = @[@"已完成的任务",@"已完成的跑腿任务",@"账号余额",@"我的统计",@"排行榜",@"我的考勤",@"通知中心",@"设置",@"异常上报"];

    
    self.cellIdentifier = @"LeftCell";
    [self layoutUI];
    [self layoutConstraints];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryData) name:NotificationUpdateUserAccount object:nil];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNeedsStatusBarAppearanceUpdate];
    if(!self.Identity.userInfo.isLogin){
        UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:[[Login alloc]init]];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        [self queryData];
        NSString* str = [NSString stringWithFormat:@"%@\n%@",self.Identity.userInfo.realName,self.Identity.userInfo.phone];
        NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
        self.labelUser.attributedText = attributeStr;
        
        NSUserDefaults* setting = [NSUserDefaults standardUserDefaults];
        
        NSInteger open =  [[setting objectForKey:@"btnOpen"] integerValue];
        NSInteger close =  [[setting objectForKey:@"btnClose"] integerValue];
        if(open == close || open > close){
            self.btnOpen.selected = YES;
            self.btnClose.selected = NO;
        }else{
            self.btnOpen.selected = NO;
            self.btnClose.selected = YES;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  user interface layout
-(void)layoutUI{
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200.f);
    [self.headerView addSubview:self.btnUser];
    [self.btnUser addSubview:self.imageIcon];
    [self.btnUser addSubview:self.labelUser];
    [self.btnUser addSubview:self.iconArrow];
    [self.headerView addSubview:self.statuView];
    [self.statuView addSubview:self.btnOpen];
    [self.statuView addSubview:self.btnClose];
    [self.statuView addSubview:self.btnBusy];

    self.tableView.tableHeaderView = self.headerView;
    [self.tableView registerClass:[LeftCell class] forCellReuseIdentifier:self.cellIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = [UIColor colorWithRed:26/255.f green:28/255.f blue:31/255.f alpha:1.0];
    self.tableView.delegate = self;
}

-(void)layoutConstraints{
    
    
    [self.btnUser mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.width.mas_equalTo(Main_Width);
        make.left.equalTo(self.view);
        make.height.mas_equalTo(160);
    }];
    
    
    [self.statuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.btnUser.mas_bottom);
        make.width.mas_equalTo(Main_Width);
        make.left.equalTo(self.btnUser);
        make.height.mas_equalTo(40);
    }];
    
    _imageIcon.layer.cornerRadius = 60/2;
    [self.imageIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(self.btnUser);
        make.left.equalTo(self.btnUser).offset(20);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    [self.labelUser mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageIcon);
        make.right.equalTo(self.btnUser);
        make.left.equalTo(self.imageIcon.mas_right).offset(5);
        make.height.equalTo(self.imageIcon);
    }];
    
    [self.iconArrow mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(self.imageIcon);
        make.right.equalTo(self.btnUser).offset(-20);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    
    
    UILabel *line1 = [[UILabel alloc] init];
    line1.backgroundColor  =[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0];
    [self.statuView addSubview:line1];
    
    UILabel *line2 = [[UILabel alloc] init];
    line2.backgroundColor  =[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0];
    [self.statuView addSubview:line2];
    
    [self.btnOpen mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.statuView);
        make.left.equalTo(self.statuView);
        make.width.mas_equalTo(self.statuView.mas_width).multipliedBy(0.33);
        
    }];
    
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.statuView);
        make.left.equalTo(self.btnOpen.mas_right);
        make.size.mas_equalTo(CGSizeMake(1, 20));
        
    }];
    
    [self.btnClose mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.btnOpen);
        make.left.equalTo(line1.mas_right);
    }];
    
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.statuView);
        make.left.equalTo(self.btnClose.mas_right);
        make.size.equalTo(line1);
        
    }];
    
    [self.btnBusy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.btnOpen);
        make.left.equalTo(line2.mas_right);
    }];
    
    
}
#pragma mark =====================================================  DataSource
-(void)queryData{

    NSDictionary* arg = @{@"ince":@"get_emp_info",@"emp_id":self.Identity.userInfo.userID};
    [DBNet PostURL:kHost parameters:arg succeed:^(NSDictionary *data) {
        [WMHelper outPutJsonString:data];
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSDictionary* emptyDict = [data objectForKey:@"info"];
            if(![WMHelper isNULLOrnil:emptyDict]){
                self.item = self.Identity.userInfo;
                self.item.dataLine = [emptyDict objectForKey:@"dataline"];
                self.item.status = [emptyDict objectForKey:@"status"];
                self.item.account = [emptyDict objectForKey:@"account"];
                self.item.lat = [emptyDict objectForKey:@"lat"];
                self.item.lng = [emptyDict objectForKey:@"lng"];
                self.item.close = [emptyDict objectForKey:@"close"];
                self.item.kf_tel = [emptyDict objectForKey:@"kf_tel"];

                Boolean flag= [NSKeyedArchiver archiveRootObject:self.item toFile:[WMHelper archiverPath]];
                
                [self.imageIcon sd_setImageWithURL:[NSURL URLWithString:emptyDict[@"user_picture"]] placeholderImage:[UIImage imageNamed:@"touxiang_placeholder"]];

                if(flag){
                    
                }else
                    NSLog(@"%@",@"归档失败!");
            }
            
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
        [self loadData];
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
    }];
    
}
-(void)UserHeaderHandle{
    
    [self.sideMenuViewController hideMenuViewController];
    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToMineDetail object:nil];
    
}
#pragma mark =====================================================  <UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayTitle.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeftCell* cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    [cell loadDataWithImage:self.arrayIcon[indexPath.row] title:self.arrayTitle[indexPath.row]];
    cell.tag = indexPath.row;
    UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureTouch:)];
    //tapgr.delegate = self;
    [cell addGestureRecognizer:tapgr];
    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return  NO;
}
#pragma mark =====================================================  SEL
-(IBAction)gestureTouch:(UIGestureRecognizer*)sender{
    if([sender.view isKindOfClass:[UITableViewCell class]]){
        switch (sender.view.tag) {
            case 0:
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToFinishedTask object:nil];
            }
                break;
            case 1:
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationRunBuyOver object:nil];
            }
                break;
            case 2:
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToAccount object:nil];
            }
                break;
            case 3:
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationMineTongJi object:nil];
            }
                break;
            case 4://排行榜
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationMineRankList object:nil];

            }
                break;
                
                
            case 5://我的考勤
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationMineCheck object:nil];

            }
                break;
                
            case 6://通知中心
            {
                [self.sideMenuViewController hideMenuViewController];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToNotification object:nil];

                
                
            }
                break;
                
                
            case 7:
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToSetting object:nil];
            }
                break;
                
                case 8:
            {
                [self.sideMenuViewController hideMenuViewController];
                [[NSNotificationCenter defaultCenter]postNotificationName:NotificationToCash object:nil];
            }
                break;
                
                
            default:
                break;
        }
        
    }else{
        
    }
}

-(void)workTime:(UIButton*)sender{

    if(sender == self.btnOpen){
        if(self.btnOpen.selected){
            NSLog(@"self.btnOpen.selected:%d",self.btnOpen.selected);
        }else{
            [self changeClose:@"1"];
        }
    }else if(sender == self.btnClose){
        
//        [self callPhone];
        
        if(self.btnClose.selected){
             NSLog(@"btnClose:%d",self.btnClose.selected);
        }else {
            [self changeClose:@"2"];

        }
    }else{
        if(self.btnBusy.selected){
            NSLog(@"btnBusy:%d",self.btnBusy.selected);
        }else {
            [self changeClose:@"3"];
        }
    }
}
-(void)callPhone{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",self.item.kf_tel];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}
#pragma mark =====================================================  private method
-(void)loadData{
    NSString* str = [NSString stringWithFormat:@"%@\n%@",self.Identity.userInfo.realName,self.Identity.userInfo.phone];
    NSMutableAttributedString* attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
    self.labelUser.attributedText = attributeStr;
    if([self.Identity.userInfo.close isEqualToString:@"1"]){
        self.btnOpen.selected = YES;
        self.btnClose.selected = NO;
        self.btnBusy.selected = NO;

    }else  if([self.Identity.userInfo.close isEqualToString:@"2"]){
        self.btnClose.selected = YES;
        self.btnOpen.selected = NO;
        self.btnBusy.selected = NO;

    }else{
        self.btnBusy.selected = YES;
        self.btnClose.selected = NO;
        self.btnOpen.selected = NO;
    }
}

-(void)changeClose:(NSString*)close{

    NSDictionary* arg = @{@"ince":@"set_emp_open",@"emp_id":self.Identity.userInfo.userID,@"close":close};
    [DBNet PostURL:kHost parameters:arg succeed:^(NSDictionary *data) {
        [WMHelper outPutJsonString:data];
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            [HBHUDTool showSuccess:data[@"sucess"]];

            [self queryData];
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
    }];
}

#pragma mark =====================================================  property package
-(UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc]init];
    }
    return _headerView;
}

-(UIButton *)btnUser{
    if(!_btnUser){
        _btnUser = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnUser.userInteractionEnabled = YES;
        [_btnUser setBackgroundImage:[UIImage imageNamed:@"icon-bg-left-header"] forState:UIControlStateNormal];
        [_btnUser addTarget:self action:@selector(UserHeaderHandle) forControlEvents:UIControlEventTouchUpInside];

    }
    return _btnUser;
}

-(UIImageView *)imageIcon{
    if(!_imageIcon){
        _imageIcon = [[UIImageView alloc]init];
        [_imageIcon setImage:[UIImage imageNamed:@"touxiang_placeholder"]];
        _imageIcon.layer.masksToBounds = YES;
    }
    return _imageIcon;
}

-(UILabel *)labelUser{
    if(!_labelUser){
        _labelUser = [[UILabel alloc]init];
        _labelUser.textColor = [UIColor whiteColor];
        _labelUser.font = [UIFont systemFontOfSize:20.f];
        _labelUser.numberOfLines = 0;
        _labelUser.lineBreakMode = NSLineBreakByCharWrapping;
    }
    return _labelUser;
}

-(UIImageView *)iconArrow{
    if(!_iconArrow){
        _iconArrow = [[UIImageView alloc]init];
        [_iconArrow setImage:[UIImage imageNamed:@"icon_right_white"]];
    }
    return _iconArrow;
}

-(UIView *)statuView{
    if(!_statuView){
        _statuView = [[UIView alloc]init];
        _statuView.backgroundColor = [UIColor colorWithRed:26/255.f green:28/255.f blue:31/255.f alpha:1.0];
        CALayer* border = [[CALayer alloc]init];
        border.frame = CGRectMake(0.f, 39.5f, SCREEN_WIDTH, 0.5f);
        border.backgroundColor = [UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0].CGColor;
        [_statuView.layer addSublayer:border];
    }
    return _statuView;
}

-(UIButton *)btnOpen{
    if(!_btnOpen){
        _btnOpen = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnOpen setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnOpen setTitleColor:[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0] forState:UIControlStateNormal];
        [_btnOpen setImage:[UIImage imageNamed:@"icon-open"] forState:UIControlStateSelected];
        [_btnOpen setImage:[UIImage imageNamed:@"icon-close"] forState:UIControlStateNormal];
        [_btnOpen setTitle:@"开工" forState:UIControlStateNormal];
//        CALayer* border = [[CALayer alloc]init];
//        border.frame = CGRectMake(SCREEN_WIDTH/2-1, 10.f, 1.f, 20.f);
//        border.backgroundColor = [UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0].CGColor;
//        [_btnOpen.layer addSublayer:border];
        [_btnOpen setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [_btnOpen addTarget:self action:@selector(workTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnOpen;
}

-(UIButton *)btnClose{
    if(!_btnClose){
        _btnClose = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnClose setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnClose setTitleColor:[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0] forState:UIControlStateNormal];
        [_btnClose setImage:[UIImage imageNamed:@"icon-open"] forState:UIControlStateSelected];
        [_btnClose setImage:[UIImage imageNamed:@"icon-close"] forState:UIControlStateNormal];
        [_btnClose setTitle:@"收工" forState:UIControlStateNormal];
        [_btnClose setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [_btnClose addTarget:self action:@selector(workTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnClose;
}
-(UIButton *)btnBusy{
    if(!_btnBusy){
        _btnBusy = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnBusy setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_btnBusy setTitleColor:[UIColor colorWithRed:113/255.f green:113/255.f blue:113/255.f alpha:1.0] forState:UIControlStateNormal];
        [_btnBusy setImage:[UIImage imageNamed:@"icon-open"] forState:UIControlStateSelected];
        [_btnBusy setImage:[UIImage imageNamed:@"icon-close"] forState:UIControlStateNormal];
        [_btnBusy setTitle:@"忙碌" forState:UIControlStateNormal];
        [_btnBusy setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [_btnBusy addTarget:self action:@selector(workTime:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnBusy;
}

@end
